const $baseUrl = '';
const $axios = axios.create({
    baseURL: $baseUrl,    
    headers: { 'X-Requested-With': 'XMLHttpRequest' },
    // `withCredentials` 表示跨域请求时是否需要使用凭证(即是否支持session)
    withCredentials: true
});


$axios.interceptors.request.use((config) => {
    return config;
}, error => {
    return Promise.reject(error);
});


$axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response.data;
}, function (error) {
    // 对响应错误做点什么
    if (error.response) {
        // The request was made and the server responded with a status code
        // that falls out of the range of 2xx
        // console.log(error.response.data);
        // console.log(error.response.status);
        // console.log(error.response.headers);
        if (error.response.status == 0) {
        	Swal.fire({
      		  icon: 'error',
      		  title: `地址 ${error.config.url} 没有响应，可能服务器不可用或者地址不正确。`,
      		  showConfirmButton: false,
      		  timer: 2000
      		}); 
            

        } else {
        	Swal.fire({
    		  icon: 'error',
    		  title: `响应错误：${error.response.status}`,
    		  showConfirmButton: false,
    		  timer: 2000
    		});            
        }

    } else if (error.request) {
        // The request was made but no response was received
        // `error.request` is an instance of XMLHttpRequest in the browser and
		// an instance of
        // http.ClientRequest in node.js
        // console.log(error.request);
    	Swal.fire({
  		  icon: 'error',
  		  title: '请求错误: ' + error.request.readyState,
  		  showConfirmButton: false,
  		  timer: 2000
  		});   
        
    } else {
        // Something happened in setting up the request that triggered an Error
        // console.log('Error', error.message);
    	Swal.fire({
    		  icon: 'error',
    		  title: '错误: ' + error.message,
    		  showConfirmButton: false,
    		  timer: 2000
    		});  
        
    }


    return Promise.reject(error);
});

const $ajax = function (getAxiosPromise, options) {

    let promise = new Promise((resolve) => {

        try {


            let loading;
            // 显示加载提示代码
            if (options && options.hasLoading) {            	
            	loading = layer.load();               
            }


            getAxiosPromise()
                .then(res => {// 处理成功响应

                    // 关闭加载提示
                    if (options && options.hasLoading) {
                        layer.close(loading);
                    }

                    // let result = res.data;//获取服务器的响应结果
                    const result = res;

                    if (!result.logined && result.logined === undefined) {
                        // 服务器响应数据无已登录标志属性logined
                        resolve(result);// 由then方法的参数（一个函数）继续处理响应结果
                        return result;
                    }

                    if (!result.logined) {
                        // 服务器响应结果的已登录标志属性logined的值为false

                    	Swal.fire({
                    		  icon: 'warning',
                    		  title:  '您已下线，请登录！',
                    		  showConfirmButton: false,
                    		  timer: 2000,
                    		  onAfterClose(){
                    			window.top.location.href = 'index.html';
                    		  }
                    		}); 

                        return result;
                    }

                    if (result.authorized === undefined) {
                        resolve(result);// 由then方法的参数（一个函数）继续处理响应结果
                        return result;

                    }

                    if (!result.authorized) {
                    	Swal.fire({
                  		  icon: 'error',
                  		  title:  '权限不足！',
                  		  showConfirmButton: false,
                  		  timer: 2000
                  		}); 
                        
                        return result;
                    }

                    // 由then方法的参数（一个函数）继续处理响应结果
                    resolve(result);

                    return result;

                })
                .catch(err => {// 处理错误响应

                    // 关闭加载提示
                    if (options && options.hasLoading) {
                        layer.close(loading);
                    }

                    console.log(err);// 控制台打印错误信息

                });

        } catch (error) {// 发生异常

            console.log(error);
            
            Swal.fire({
    		  icon: 'error',
    		  title:  '错误:' + error.message,
    		  showConfirmButton: false,
    		  timer: 2000
        	});            

            throw error;

        }

    });

    return promise;

};


const $myoprate = function (getAxiosPromise, options) {

    let promise = new Promise((resolve) => {

        if (options && options.title) {
        	
        	
        	Swal.fire({
    		  title: options.title,
    		  text: options.message,
    		  type: 'warning',
    		  showCancelButton: true,
    		  confirmButtonColor: '#3085d6',
    		  cancelButtonColor: '#d33',
    		  confirmButtonText: '确定',
    		  cancelButtonText: '取消'
    			  
    		}).then((result) => {
    			
    		  if (result.value) {
    			  
                  options.hasLoading = true;// 默认带有加载提示
                  $ajax(getAxiosPromise, options)
                      .then((result) => {

                          if (result.success) {


                              if (options && options.postMsg) {// 是否提示后执行函数
                            	  
                            	  Swal.fire({
                            		  icon: 'success',
                            		  title: result.message,
                            		  showConfirmButton: false,
                            		  timer: (options && options.duration && !isNaN(options.duration)) ? parseInt(options.duration) : 2000,
                            		  onAfterClose(){
                            			  resolve(result);
                              		  }
                                	});        
                            	  
                                  

                              } else {
                            	  
                            	  Swal.fire({
                            		  icon: 'success',
                            		  title: result.message,
                            		  showConfirmButton: false,
                            		  timer: (options && options.duration && !isNaN(options.duration)) ? parseInt(options.duration) : 2000,
                            		  
                                	});  

                                  
                                  resolve(result);


                              }

                          } else {
                        	  
                        	  Swal.fire({
                        		  icon: 'error',
                        		  title: result.message,
                        		  showConfirmButton: true,
                        		  confirmButtonText: '确定'
                            	}); 
                          }

                          return result;

                      });  
    			  
    		    
    		  }
    		  
    		});

            
        } else {

            if (!options) options = {};

            options.hasLoading = true;// 默认具有加载提示
            $ajax(getAxiosPromise, options)
                .then((result) => {

                    if (result.success) {

                        if (options && options.postMsg) {// 是否提示后执行函数
                        	
                        	
                        	 Swal.fire({
                        		 icon: 'success',
	                       		 title: result.message,
	                       		 showConfirmButton: false,
	                       		 timer: (options && options.duration && !isNaN(options.duration)) ? parseInt(options.duration) : 2000,
	                       		 onAfterClose(){
	                       			 resolve(result);
	                         	 }
	                         });  

                            


                        } else {
                        	Swal.fire({
                      		  icon: 'success',
                      		  title: result.message,
                      		  showConfirmButton: false,
                      		  timer: (options && options.duration && !isNaN(options.duration)) ? parseInt(options.duration) : 2000,                      		  
                          	}); 
                        	
                            resolve(result);
                        }



                    } else {

                    	Swal.fire({
                  		  icon: 'error',
                  		  title: result.message,
                  		  showConfirmButton: true,
                  		  confirmButtonText: '确定'
                      	}); 

                    }

                    return result;

                });


        }

    });

    return promise;

};

const http_get = function (url,params , config) {

    let promise = new Promise((resolve) => {
    	
    	if(params){
    		if(config){
    			config.params = params;
    		}else{
    			config = {params};
    		}
    	}else{
    		config = {};
    	}
    	
    	config.hasLoading = (config.hasLoading===undefined || config.hasLoading===null || config.hasLoading === true)?true:false;

        $ajax(() => $axios.get(url, config), config)
            .then((result) => {
                resolve(result);
                return result;
            });

    });

    return promise;
};

const http_post_payload = function (url, data, config) {

    return $myoprate(() => $axios.post(url, data, config), config);

};

const http_put = function (url, data, config) {

    return $myoprate(() => $axios.put(url, data, config), config);

};

const http_delete = function (url,data, config) {
	
	if(data){
		if(config){
			config.data = data;
		}else{
			config = {data};
		}
	}else{
		config = {};
	}

    return $myoprate(() => $axios.delete(url, config), config);

};



/*
 * 以application/x-www-form-urlencoded编码格式，向服务器发出post请求，返回promise，
 * then方法的参数是一个函数，该函数的参数为服务器发送的未经包装响应数据
 */
const http_post = function (url, data, config) {
    if (!config) {
        config = {};
    }

    if (!config.headers) {
        config.headers = { "Content-Type": 'application/x-www-form-urlencoded' };
    } else {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }

    config.transformRequest = [function (data) {

        if (!data || typeof (data) === 'string') {
            return data;
        }

        if (!(typeof (data) === 'object')) {
            return data;
        }


        let params = [];
        for (let prop in data) {
            if (data[prop] instanceof Array) {
                let arr = data[prop];
                for (let i = 0; i < arr.length; i++) {
                    params.push(prop + "=" + arr[i]);
                }
            } else {
                params.push(prop + "=" + data[prop]);
            }

        }
        return params.join("&");

    }];

    return $myoprate(() => $axios.post(url, data, config), config);

};

